<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ title }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleForm" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep === 2" class="form-container">
        <div class="tree-wrapper">
          <div v-for="item in treeData" :key="item.id" class="tree-item">
            <div class="tree-title">{{ item.title }}</div>
            <el-tree
              ref="tree"
              :data="item.children"
              show-checkbox
              default-expand-all
              node-key="id"
              highlight-current
              :props="{ label: 'title' }"
            />
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in diabledTreeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="{ label: 'title'}"
                />
              </div>
            </div>
          </div>
        </div>
      </div></main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-show="activeStep > 1" @click="decreseStep">上一步</el-button>
        <el-button v-show="activeStep < 3" type="primary" @click="increseStep">下一步</el-button>
        <el-button v-show="activeStep === 3" type="primary" @click="submitBtn">确认添加</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getRolePermission, addDisable, addRole, getRolePermissionAndUser, editRole } from '@/api/role'
export default {
  name: 'AddRole',
  data() {
    return {
      activeStep: 1,
      title: '添加角色',
      treeData: [],
      diabledTreeList: [],
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    activeStep(newVal) {
      if (newVal === 3) {
        this.$nextTick(() => {
          this.setDisabledTreeChecked()
        })
      } else if (newVal === 2 && this.$route.params.id) {
        // 当编辑模式下进入第二步时，确保权限树被正确选中
        this.$nextTick(() => {
          this.setTreeChecked()
        })
      }
    }
  },
  async mounted() {
    await this.getTreeData()
    if (this.$route.params.id) {
      this.title = '编辑角色'
      await this.getRoleInfo(this.$route.params.id)
    } else {
      this.title = '添加角色'
    }
  },
  methods: {
    async getRoleInfo(id) {
      try {
        const { data } = await getRolePermissionAndUser(id)
        if (!data) {
          this.$message.error('获取角色信息失败')
          return
        }
        const { perms, remark, roleId, roleName } = data
        // 确保perms是有效的数组
        const validPerms = Array.isArray(perms) ? perms : []
        this.roleForm = {
          perms: validPerms,
          remark: remark || '',
          roleId,
          roleName: roleName || ''
        }
        // 如果当前是第二步，立即设置树的选中状态
        if (this.activeStep === 2) {
          this.$nextTick(() => {
            this.setTreeChecked()
          })
        }
      } catch (error) {
        console.error('获取角色信息失败:', error)
        this.$message.error('获取角色信息失败')
      }
    },
    // 设置权限树的选中状态
    setTreeChecked() {
      if (!this.$refs.tree || !Array.isArray(this.roleForm.perms)) return
      this.$refs.tree.forEach((tree, index) => {
        const permsArray = Array.isArray(this.roleForm.perms[index]) ? this.roleForm.perms[index] : []
        tree.setCheckedKeys(permsArray)
      })
    },
    // 设置禁用树的选中状态
    setDisabledTreeChecked() {
      if (!this.$refs.diabledTree || !Array.isArray(this.roleForm.perms)) return

      this.$refs.diabledTree.forEach((tree, index) => {
        const permsArray = Array.isArray(this.roleForm.perms[index]) ? this.roleForm.perms[index] : []
        tree.setCheckedKeys(permsArray)
      })
    },
    async increseStep() {
      if (this.activeStep === 3) return

      if (this.activeStep === 1) {
        try {
          await this.$refs.roleForm.validate()
          this.activeStep++
        } catch (error) {
          return
        }
      } else if (this.activeStep === 2) {
        // 收集权限数据
        const newPerms = []
        if (this.$refs.tree) {
          this.$refs.tree.forEach(tree => {
            newPerms.push(tree.getCheckedKeys())
          })
        }

        // 检查是否有选中的权限
        const hasPermissions = newPerms.some(arr => arr && arr.length > 0)
        if (!hasPermissions) {
          this.$message.error('请选择权限')
          return
        }

        // 更新权限数据
        this.roleForm.perms = newPerms
        this.activeStep++
      }
    },
    decreseStep() {
      if (this.activeStep > 1) {
        this.activeStep--
      }
    },
    async submitBtn() {
      try {
        if (this.$route.params.id) {
          // 编辑角色
          await editRole({
            ...this.roleForm,
            roleId: this.$route.params.id
          })
          this.$message.success('编辑成功')
        } else {
          // 添加角色
          await addRole(this.roleForm)
          this.$message.success('添加成功')
        }
        this.$router.back()
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交失败')
      }
    },
    async getTreeData() {
      try {
        const { data } = await getRolePermission()
        if (!data) {
          this.$message.error('获取树形数据失败')
          return
        }

        this.treeData = data
        this.diabledTreeList = JSON.parse(JSON.stringify(data))
        addDisable(this.diabledTreeList)
      } catch (error) {
        console.error('获取树形数据失败:', error)
        this.$message.error('获取树形数据失败')
      }
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex:1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info{
          font-size:14px;
          color:#666;
          .form-item{
            margin-bottom:20px;
          }
        }
      }
      .form-box{
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      .tree-item {
        flex: 1;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }
}
</style>
